package com.star.controller.admin;


import com.star.pojo.User;
import com.star.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * 博客后台登录  控制器
 */
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 去后台登录页面
     *
     */
    @GetMapping
    public String loginPage() {
        return "admin/login";
    }

    /**
     * 后台登录
     *
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {

        User user = userService.checkUser(username, password);

        if (user != null) {
            user.setPassword(null);
            session.setAttribute("user",user);
            return "admin/index";
        } else {

            attributes.addFlashAttribute("message", "用户名和密码错误");  //这里不能用Model

            return "redirect:/admin";   //重定向到登录页面
        }
    }

    /**
     *  退出登录
     *
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {

        session.removeAttribute("user");  //清空session

        return "redirect:/admin";
    }


}
